package com.jinyi.wwdeng.ui.main.impl

import android.content.Context
import com.jinyi.base.mvp.BasePresenter
import com.jinyi.wwdeng.AppConfigs
import com.jinyi.wwdeng.status.StatusRepository
import com.jinyi.wwdeng.ui.main.contract.CreditApplyContract
import org.json.JSONObject

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/28 16:21
 * @Annotation：Presenter 实现类
 */
class CreditApplyPresenterImpl: BasePresenter<CreditApplyContract.View,CreditApplyModelImpl>(),CreditApplyContract.Presenter {

    override fun createModel(): CreditApplyModelImpl {
        return CreditApplyModelImpl(this)
    }

    /**
     * 获取用户贷款额度预览信息
     */
    fun loadCreditApplyRequest(){
        if (isViewDestory()) {
            return
        }
        model!!.loadCreditApplyRequest()
    }
    /**
     * 从数据中获取用户总流程
     * 流程
     * 1、需要先通过总流程接口，判断订单状态和申请状态
     * 2、创建贷款申请订单
     * 3、创建贷款申请订单成功后再验证总流程，返回首页显示审核状态
     */
    fun loadProcessData(){
        val data = JSONObject(AppConfigs.getSPString(AppConfigs.SP_KEY.SP_HENECREDIT_PROCESS))
        //1、判断是否存在 订单状态
        if (data.has("orderStatus")){
            val orderStatus = data.optString("orderStatus")
            //待还款 || 放款中 || 申请贷款被拒绝
            if (StatusRepository(null,orderStatus).isRepayNow() || StatusRepository(null,orderStatus).isDisbursing() || StatusRepository(null,orderStatus).isRejected()){
                mvpView!!.showCreditApplyFailed()
                return
            }
        }

        //2、判断是否存在 贷款申请状态
        if (data.has("applyStatus")){
            val applyStatus = data.optString("applyStatus")
            //审核中 || 被拒绝
            if (StatusRepository(applyStatus).isReviewing() || StatusRepository(applyStatus).isRejected()){
                mvpView!!.showCreditApplyFailed()
                return
            }
        }

        //3、创建贷款订单
        model!!.onSubmitCreditApplyOrderRequest()
    }

    /**
     * 获取用户贷款额度预览信息成功
     */
    override fun onCreditApplyInfoSuccess(data: JSONObject) {
        if (isViewDestory()) {
            return
        }
        when(data.optInt("code")){
            0 -> {//成功
                val obj = data.optJSONObject("obj")
                mvpView!!.showCreditApplyInfoData(obj)
            }
            else -> {//失败
                mvpView!!.showToast(data.optString("msg"))
            }
        }
    }

    /**
     * 创建贷款申请订单成功
     */
    override fun onCreditApplyOrderCreateSuccess(data: JSONObject) {
        if (isViewDestory()) {
            return
        }
        when(data.optInt("code")){
            0 -> {//成功
                mvpView!!.showCreditApplyOrderCreateSuccess(data)
            }
            else -> {//失败
                mvpView!!.showToast(data.optString("msg"))
            }
        }
    }

    override fun onRequestFinish() {
        mvpView!!.onRequestFinish()
    }

    override val context: Context?
        get() = if (!isViewDestory()) {
            mvpView!!.getContext()
        } else null
}